import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import { useLoginUserStore } from "@/store/userStore";
import ACCESS_ENUM from "@/access/accessEnum";
import { message } from "ant-design-vue";
import checkAccess from "@/access/checkAccess";
import HomeView from "@/views/HomeView.vue";
import QuizCompetitionView from "@/views/activity/QuizCompetitionView.vue";
import QuizDetailView from "@/views/activity/QuizDetailView.vue";
import PrizeRedemptionView from "@/views/activity/PrizeRedemptionView.vue";

// 定义带权限的路由配置
type AuthRoute = RouteRecordRaw & {
  meta?: {
    access?: (typeof ACCESS_ENUM)[keyof typeof ACCESS_ENUM];
    requireAuth?: boolean;
  };
};

const routes: AuthRoute[] = [
  {
    path: "/",
    name: "home",
    component: HomeView,
    meta: {
      access: ACCESS_ENUM.NOT_LOGIN,
    },
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/auth/LoginPage.vue"),
    meta: {
      access: ACCESS_ENUM.NOT_LOGIN,
    },
  },
  {
    path: "/shop",
    name: "ProductList",
    component: () => import("@/views/shop/ProductListView.vue"),
  },
  {
    path: "/shop/product/:id",
    name: "ProductDetail",
    component: () => import("@/views/shop/ProductDetailView.vue"),
  },
  {
    path: "/shop/store/:id",
    name: "StoreDetail",
    component: () => import("@/views/shop/StoreDetailView.vue"),
  },
  // {
  //   path: "/creator",
  //   name: "creator",
  //   component: () => import("@/views/CreatorView.vue"),
  //   meta: {
  //     requireAuth: true,
  //     access: ACCESS_ENUM.CREATOR,
  //   },
  // },
  {
    path: "/register",
    name: "register",
    component: () => import("@/views/auth/RegisterPage.vue"),
    meta: {
      access: ACCESS_ENUM.NOT_LOGIN,
    },
  },
  {
    path: "/aboutus",
    component: () => import("@/views/aboutus/AboutLayoutView.vue"),
    children: [
      {
        path: "about",
        name: "about",
        component: () => import("@/views/aboutus/AboutUsView.vue"),
      },
      {
        path: "contact",
        name: "contact",
        component: () => import("@/views/aboutus/ContactUsView.vue"),
      },
      {
        path: "feedback",
        name: "feedback",
        component: () => import("@/views/aboutus/FeedbackView.vue"),
      },
    ],
  },
  {
    path: "/shop/payment",
    name: "payment",
    component: () => import("@/views/shop/PaymentView.vue"),
    meta: {
      requireAuth: true,
      title: "订单支付",
    },
  },
  {
    path: "/order",
    component: () => import("@/views/order/OrderLayoutView.vue"),
    meta: {
      requireAuth: true,
    },
    children: [
      {
        path: "create",
        name: "CreateOrder",
        component: () => import("@/views/order/CreateOrderView.vue"),
        meta: {
          requireAuth: true,
          title: "创建订单",
        },
      },
      {
        path: ":id",
        name: "OrderDetail",
        component: () => import("@/views/order/OrderDetailView.vue"),
      },
    ],
  },
  {
    path: "/user",
    component: () => import("@/views/user/UserCenterView.vue"),
    meta: {
      requireAuth: true,
    },
    children: [
      {
        path: "",
        name: "UserDetail",
        component: () => import("@/views/user/UserDetailView.vue"),
      },
      {
        path: "cart",
        name: "UserCart",
        component: () => import("@/views/shop/CartView.vue"),
      },
      {
        path: "order",
        name: "UserOrder",
        component: () => import("@/views/order/OrdersView.vue"),
      },
      {
        path: "points",
        name: "UserPoints",
        component: () => import("@/views/user/UserPointsView.vue"),
      },
      {
        path: "address",
        name: "UserAddress",
        component: () => import("@/views/address/AddressListView.vue"),
      },
    ],
  },
  {
    path: "/culture",
    name: "Culture",
    component: () => import("@/views/culture/CultureLayoutView.vue"),
    children: [
      {
        path: "history",
        name: "ClothingHistory",
        component: () =>
          import("@/views/culture/history/HistoryTimelineView.vue"),
      },
      {
        path: "history/period/:id",
        name: "PeriodDetail",
        component: () => import("@/views/culture/history/PeriodDetailView.vue"),
      },
      {
        path: "discussion",
        name: "Discussion",
        component: () =>
          import("@/views/culture/discussion/DiscussionListView.vue"),
      },
      {
        path: "discussion/:id",
        name: "DiscussionDetail",
        component: () =>
          import("@/views/culture/discussion/DiscussionDetailView.vue"),
      },
      {
        path: "story",
        name: "StoryList",
        component: () => import("@/views/culture/story/StoryListView.vue"),
      },
      {
        path: "story/:id",
        name: "StoryDetail",
        component: () => import("@/views/culture/story/StoryDetailView.vue"),
      },
    ],
  },
  {
    path: "/address",
    name: "AddressList",
    component: () => import("@/views/address/AddressListView.vue"),
    meta: {
      requiresAuth: true,
      title: "地址管理",
    },
  },
  {
    path: "/address/add",
    name: "AddressAdd",
    component: () => import("@/views/address/AddressEditView.vue"),
    meta: {
      requiresAuth: true,
      title: "新增地址",
    },
  },
  {
    path: "/address/edit/:id",
    name: "AddressEdit",
    component: () => import("@/views/address/AddressEditView.vue"),
    meta: {
      requiresAuth: true,
      title: "编辑地址",
    },
  },
  {
    path: "/activity/quiz-competition",
    name: "quiz-competition",
    component: QuizCompetitionView,
  },
  {
    path: "/activity/prize-redemption",
    name: "prize-redemption",
    component: PrizeRedemptionView,
  },
  {
    path: "/activity/quiz-competition/:id",
    name: "quiz-answer",
    component: QuizDetailView,
    meta: {
      requireAuth: true,
      title: "知识竞赛答题",
    },
  },
  {
    path: "/customer-service/:storeId/:productId",
    name: "CustomerService",
    component: () => import("@/views/CustomerServiceView.vue"),
    meta: {
      title: "在线客服",
      requiresAuth: true,
    },
  },
  {
    path: "/:pathMatch(.*)*",
    name: "notFound",
    component: () => import("@/views/NotFound.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 全局路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useLoginUserStore();

  // 如果没有登录信息，先获取登录信息
  if (!userStore.loginUser.userRole) {
    await userStore.fetchLoginUser();
  }

  const { requireAuth, access } = to.meta ?? {};
  const currentRole = userStore.loginUser.userRole;

  // 如果页面需要登录
  if (requireAuth) {
    if (currentRole === ACCESS_ENUM.NOT_LOGIN) {
      message.warning("请先登录");
      next("/login");
      return;
    }
  }

  // 权限判断
  if (access) {
    // 检查用户是否有权限访问
    if (!checkAccess(userStore.loginUser, access)) {
      if (currentRole === ACCESS_ENUM.NOT_LOGIN) {
        message.warning("请先登录");
        next("/login");
      } else {
        message.error("");
        next(from.path);
      }
      return;
    }
  }

  next();
});

export default router;
